package com.tax.config.filter;
;
import com.alibaba.fastjson.JSONObject;
import com.tax.common.constant.CommonConstant;
import com.tax.common.util.SpringUtils;
import com.tax.common.util.StringsUtil;
import com.tax.config.jwt.JwtUserInfo;
import com.tax.config.response.Response;
import com.tax.config.response.ResponseCode;
import com.tax.dto.req.TokenReq;
import com.tax.entity.TdUser;
import com.tax.enums.LoginTypeEnum;
import com.tax.manager.AccessTokenManager;
import com.tax.manager.RedisApiManager;
import com.tax.service.ITdUserService;
import lombok.extern.slf4j.Slf4j;
import org.junit.platform.commons.util.StringUtils;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * 路径拦截处理
 */
@Slf4j
public class UserInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("这里是鉴权信息拦截处理");
        try {
            String token = request.getHeader("token");
            if (StringUtils.isBlank(token)) {
                doResult(response, ResponseCode.TOKEN_ERROR.getCode(),"用户授权校验失败");
                return false;
            }
            AbstractApplicationContext context = SpringUtils.getAbstractApplicationContext(request);
            StringRedisTemplate stringRedisTemplate = (StringRedisTemplate)context.getBean("stringRedisTemplate");
            AccessTokenManager accessTokenManager = (AccessTokenManager)context.getBean(CommonConstant.ACCESS_TOEKN_MANAGERR);
            JwtUserInfo jwtUserInfo = accessTokenManager.getJwtUserInfo(token);
            if (null == jwtUserInfo) {
                doResult(response, ResponseCode.TOKEN_ERROR.getCode(),"用户授权校验失败");
                return false;
            }
            String tokenKey = "";
            //验证码登录
            if (jwtUserInfo.getUserLoginType().equals(CommonConstant.USER_ACCESS_TOKEN_TYPE_VALIDCODE)) {
                tokenKey = StringsUtil.getUserValidcodeLoginKey(jwtUserInfo.getTelephone());
            }
            //密码登录
            if (jwtUserInfo.getUserLoginType().equals(CommonConstant.USER_ACCESS_TOKEN_TYPE_PASSWORD)) {
                tokenKey = StringsUtil.getUserPasswordLoginKey(jwtUserInfo.getTelephone());
            }
            if (!stringRedisTemplate.hasKey(tokenKey)) {
                doResult(response, ResponseCode.TOKEN_ERROR.getCode(),"用户授权校验失败");
                return false;
            }
            stringRedisTemplate.expire(tokenKey,CommonConstant.ACCESS_TOKEN_EXPIRE, TimeUnit.DAYS);
        } catch (Exception e) {
            log.error(e.getMessage());
            doResult(response, ResponseCode.TOKEN_ERROR.getCode(),e.getMessage());
            return false;
        }
        return true;
    }

    public void doResult(HttpServletResponse response,int code,String message) {
        Response resultResponse = new Response(code,message);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.append(JSONObject.toJSONString(resultResponse));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }

}
